package com.atguigu.producer;

import com.atguigu.callback.MyCallBack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Date;

@Slf4j
@RequestMapping("ttl")
@RestController
public class ConfirmController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MyCallBack myCallBack;

    //为了确保myCallBack能注入到rabbitTemplate
    @PostConstruct
    public void init() {
        //交换机接收到消息之后的一个回调方法
        //rabbitTemplate.setConfirmCallback(myCallBack);
        /**
         * setMandatory
         * true 交换机无法将消息进行路由的时候,将消息返回给生产者
         * false 交换机无法将消息进行路由的时候,直接丢弃
         */
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(myCallBack);
    }


    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";

    @GetMapping("sendMessage/{message}")
    public void sendMessage(@PathVariable String message) {
        //交换机接受到消息之后的一个回调方法
        rabbitTemplate.setConfirmCallback(myCallBack);

        //指定消息id为1
        CorrelationData correlationData1 = new CorrelationData("1");
        String routingKey = "key1";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME, routingKey, message + routingKey, correlationData1);

        CorrelationData correlationData2 = new CorrelationData("2");
        routingKey = "key2";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME, routingKey, message + routingKey, correlationData2);
        log.info("发送消息内容:{}", message);
    }

}
